use crate::app::bottom_status::BottomStatus;
use crate::app::node_container::NodeContainer;
use crate::app::node_list::NodeListUI;
use crate::app::top_menu::TopMenu;
use crate::config::AppConfig;
use crate::data::Node;
use eframe::egui;
use std::sync::Arc;

mod node_list;
mod top_menu;
mod bottom_status;
mod node_container;
mod tab_bar;
mod node_struct;
mod node_attribute;
mod node;
mod node_item;

pub trait UIComponent {
    fn update(&mut self, ui: &mut egui::Ui);
}

pub struct BehaviorTreeApp {
    // ui组件
    ui_components: Vec<Box<dyn UIComponent>>,
}

impl BehaviorTreeApp {
    pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
        let ctx = &cc.egui_ctx;
        AppConfig::set(ctx);
        let node = Node::new().with_title(String::from("根节点"));
        let root = node.into();
        Node::set_root_node(ctx, Arc::clone(&root));
        Node::set_list_root_node(ctx, Arc::clone(&root));
        Node::set_current_node(ctx, Arc::clone(&root));
        let app = BehaviorTreeApp {
            ui_components: vec![
                Box::new(TopMenu::new()),
                Box::new(BottomStatus::new()),
                Box::new(NodeListUI::new()),
                Box::new(NodeContainer::new()),
            ],
        };
        app.load_font(ctx);
        app
    }

    // 加载中文字体
    fn load_font(&self, ctx: &egui::Context) {
        let mut fonts = egui::FontDefinitions::default();
        fonts.font_data.insert(
            "chinese font".to_owned(),
            egui::FontData::from_static(include_bytes!("../../resources/simsun.ttc")).into(),
        );

        fonts.families
            .entry(egui::FontFamily::Proportional)
            .or_default()
            .insert(0, "chinese font".to_owned());

        fonts.families
            .entry(egui::FontFamily::Monospace)
            .or_default()
            .push("chinese font".to_owned());

        ctx.set_fonts(fonts);
    }
}

impl eframe::App for BehaviorTreeApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            self.ui_components.iter_mut().for_each(|ui_component| {
                ui_component.update(ui);
            });
        });
    }
}
